package com.jtlrm.ckd.mvp.view.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.base.sdk.base.net.CommonObserver;
import com.base.sdk.util.CommonUtil;
import com.base.sdk.util.DateFormatUtil;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.haibin.calendarview.Calendar;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.base.acitvity.BaseActivity;
import com.jtlrm.ckd.entity.PageEntity;
import com.jtlrm.ckd.entity.SuiFangPaiBanEntity;
import com.jtlrm.ckd.entity.event.SuiFangUpdateMessage;
import com.jtlrm.ckd.mvp.model.SuiFangPaiBanModel;
import com.jtlrm.ckd.mvp.view.adapter.SuiFangPaiBanSearchAdapter;
import com.jtlrm.ckd.util.EventBusUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import ezy.ui.layout.LoadingLayout;

/**
 *
 */
public class SuiFangPaiBanSearchActivity extends BaseActivity implements SwipeItemClickListener {

    @BindView(R.id.recyclerView)
    SwipeMenuRecyclerView recyclerView;
    SuiFangPaiBanSearchAdapter adapter;
    @BindView(R.id.search_content)
    EditText searchContent;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    Long currentTime; // 当前要搜索的日期
    private int pageNum = 1;
    private int pageSize = 12;
    TextView info;
    private TimePickerView pvCustomLunar;
    SuiFangPaiBanModel paiBanModel;
    SuiFangPaiBanEntity changedPerson; // 要被修改的人
    String keyWord;
    @BindView(R.id.back)
    ImageView backI;
    @BindView(R.id.loading)
    LoadingLayout loadingLayout;
    @BindView(R.id.clear_search)
    ImageView clearSearchI;
    DateFormatUtil dateFormatUtil;

    public static void goSearch(Context context) {
        Intent intent = new Intent(context, SuiFangPaiBanSearchActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_sui_fang_pai_ban_search);
    }

    @Override
    protected void initView() {
        paiBanModel = new SuiFangPaiBanModel();
        adapter = new SuiFangPaiBanSearchAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(createItemDecoration());
        recyclerView.setSwipeItemClickListener(this);
        recyclerView.setAdapter(adapter);
        initLunarPicker();
        showEmpty();
        dateFormatUtil = new DateFormatUtil();
    }

    @Override
    protected void obtainData() {

    }

    @Override
    protected void initEvent() {
        searchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    CommonUtil.hideSoftInput(context, searchContent);
                    keyWord = searchContent.getText() + "";
                    if (!notEmpty(keyWord)) {
                        showToast("搜索内容不能为空");
                    } else {
                        loadingLayout.showContent();
                        CommonUtil.hideSoftInput(context, searchContent);
                        smartRefreshLayout.autoRefresh();
                    }
                }
                return false;
            }
        });
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageNum++;
                loadData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                loadData();
            }
        });
        adapter.setMenuOnClick(new SuiFangPaiBanSearchAdapter.MenuOnClick() {
            @Override
            public void addSuiFang(SuiFangPaiBanEntity item) {
                changedPerson = item;
                addData(item.getName());
            }

            @Override
            public void changeDate(SuiFangPaiBanEntity item) {
                changedPerson = item;
                changeData(item.getName(), item.getVisitTime());
            }

            @Override
            public void deletePaiBan(SuiFangPaiBanEntity item) {
                changedPerson = item;
                deletePerson();
            }
        });
        backI.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        clearSearchI.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setText(searchContent, "");
                smartRefreshLayout.autoRefresh();
            }
        });
    }

    public void changeData(String huanzhe, String date) {
        if (info != null && pvCustomLunar != null) {
            info.setText(Html.fromHtml("患者" + huanzhe + "的随访日期从<font color= '#FF8B00'>" + date + "</font><br>更改到:"));
            pvCustomLunar.show();
        }
    }

    public void addData(String huanzhe) {
        if (info != null && pvCustomLunar != null) {
            info.setText(Html.fromHtml("患者" + huanzhe + "下次的随访时间为:"));
            pvCustomLunar.show();
        }
    }


    /**
     * 修改随访时间
     */
    private void changeSuiFang() {
        if (changedPerson == null) {
            return;
        }
        if (isGoneTime(currentTime)) {
            showToast("不能修改随访时间到过去");
            return;
        }
        showLoadingDialog("修改中");
        paiBanModel.changeSuiFang(DateFormatUtil.dateFormatLine(currentTime), changedPerson.getId(), new CommonObserver<String>() {
            @Override
            public void onError(int errType, String errMessage) {
                dismissLoadingDialog();
                showToast(errMessage);
            }

            @Override
            public void onResult(String data) {
                dismissLoadingDialog();
                showToast("修改成功");
                EventBusUtil.postEvent(new SuiFangUpdateMessage());
                smartRefreshLayout.autoRefresh();
            }
        }, lifecycleSubject);
    }

    private void add() {
        if (changedPerson == null) {
            return;
        }
        if (isGoneTime(currentTime)) {
            showToast("不能修改随访时间到过去");
            return;
        }
        showLoadingDialog("增加中");
        paiBanModel.addSuiFang(DateFormatUtil.dateFormatLine(currentTime), changedPerson.getId(), new CommonObserver<String>() {
            @Override
            public void onError(int errType, String errMessage) {
                dismissLoadingDialog();
                showToast(errMessage);
            }

            @Override
            public void onResult(String data) {
                showToast("增加成功");
                dismissLoadingDialog();
                EventBusUtil.postEvent(new SuiFangUpdateMessage());
                smartRefreshLayout.autoRefresh();
            }
        }, lifecycleSubject);
    }

    private void deletePerson() {
        if (changedPerson == null) {
            return;
        }
        showLoadingDialog("移除中");
        paiBanModel.deleteSuiFang(changedPerson.getId(), new CommonObserver<String>() {
            @Override
            public void onError(int errType, String errMessage) {
                dismissLoadingDialog();
                showToast(errMessage);
            }

            @Override
            public void onResult(String data) {
                dismissLoadingDialog();
                showToast("移除成功");
                EventBusUtil.postEvent(new SuiFangUpdateMessage());
                smartRefreshLayout.autoRefresh();
            }
        }, lifecycleSubject);
    }

    /**
     * 加载数据
     */
    public void loadData() {
        paiBanModel.querySuiFangList(keyWord, "", pageNum, pageSize, new CommonObserver<PageEntity<List<SuiFangPaiBanEntity>>>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                closeFrshorLoadmore();
                showEmpty();
            }

            @Override
            public void onResult(PageEntity<List<SuiFangPaiBanEntity>> data) {
                if (pageNum == 1) {
                    adapter.replaceData(data.getItems());
                } else {
                    adapter.addData(data.getItems());
                }
                if (data.getItems().size() < pageSize) {
                    smartRefreshLayout.setEnableLoadmore(false);
                } else {
                    smartRefreshLayout.setEnableLoadmore(true);
                }
                closeFrshorLoadmore();
                showEmpty();
            }
        }, lifecycleSubject);
    }

    /**
     * 农历时间已扩展至 ： 1900 - 2100年
     */
    private void initLunarPicker() {
        java.util.Calendar selectedDate = java.util.Calendar.getInstance();//系统当前时间
        java.util.Calendar startDate = java.util.Calendar.getInstance();
        startDate.set(2000, 1, 23);
        java.util.Calendar endDate = java.util.Calendar.getInstance();
        endDate.set(2100, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomLunar = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                currentTime = date.getTime();
            }
        }).setDate(selectedDate).setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.suifang_date_select, new CustomListener() {
                    @Override
                    public void customLayout(final View v) {
                        info = v.findViewById(R.id.info);
                        v.findViewById(R.id.queren).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomLunar.returnData();
                                pvCustomLunar.dismiss();
                                if (notEmpty(changedPerson.getVisitTime())) {
                                    changeSuiFang();
                                } else {
                                    add();
                                }
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(Color.GRAY)
                .build();
    }


    protected RecyclerView.ItemDecoration createItemDecoration() {
        return new DefaultItemDecoration(ContextCompat.getColor(this, R.color.margin_background), 2, 11, -1);
    }

    @Override
    public void onItemClick(View itemView, int position) {

    }

    /**
     * 关闭加载更多或者刷新
     */
    private void closeFrshorLoadmore() {
        if (smartRefreshLayout.isLoading()) {
            smartRefreshLayout.finishLoadmore();
        }
        if (smartRefreshLayout.isRefreshing()) {
            smartRefreshLayout.finishRefresh();
        }
    }

    public void showEmpty() {
        if (adapter.getData() == null || adapter.getData().size() == 0) {
            loadingLayout.showEmpty();
        } else {
            loadingLayout.showContent();
        }
    }

    /**
     * 判断是否是过去时间
     * @param date
     * @return
     */
    public boolean isGoneTime(Long date) {
        try {
            String string = DateFormatUtil.dateFormatLine(System.currentTimeMillis());
            Long curent = dateFormatUtil.getCalendar(string).getTime().getTime();
            if (curent > date) {
                return true;
            } else {
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }
}
